package templates_handel

import (
	"ToolLibray/excel_templates"
	"fmt"

	"github.com/xuri/excelize/v2"
)

func DeptCostsHandel(unit string, timeStr string, list []map[string]interface{}) (*excelize.File, error) {
	f, err := excelize.OpenFile("./templates/dept_costs_template.xlsx") //读取模板
	if err != nil {
		return nil, err
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	sheetName := f.GetSheetName(0) // 0 表示第一个工作表

	// 获取工作表中指定单元格的值
	unitStr := fmt.Sprintf("单位：___%s___", unit)
	err = f.SetCellStr(sheetName, "A3", unitStr)
	if err != nil {
		return nil, err
	}

	time := excel_templates.ParseDateOrDefault(timeStr)
	yyyy, mm, _ := excel_templates.GetDateComponents(time)
	dateStr := fmt.Sprintf("__%d__月__%02d__日", yyyy, mm)
	err = f.SetCellStr(sheetName, "B3", dateStr)
	if err != nil {
		return nil, err
	}

	data_start_row := 9
	start_col := "A"
	end_col := "I"

	// 输出 list 中的每个 map
	excel_templates.FillExcelWithData(f, sheetName, list, start_col, end_col, data_start_row)
	return f, nil
}
